package com.ykdl.member.kid.person;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import net.wxxr.dataparse.model.DataParseError;
import net.wxxr.dataparse.model.DataState;
import net.wxxr.http.interfaces.ITag;
import android.content.ContentValues;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore.Images;
import android.support.v4.view.PagerAdapter;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.lidroid.xutils.BitmapUtils;
import com.ykdl.member.kid.R;
import com.ykdl.member.KidApp;
import com.ykdl.member.http.Network;
import com.ykdl.member.kid.beans.DiaryBean;
import com.ykdl.member.kid.beans.StatuResult;
import com.ykdl.member.kid.fittool.BaseActivity;
import com.ykdl.member.kid.image.ImageUtil;
import com.ykdl.member.kid.util.SysUtil;
import com.ykdl.member.views.HackyViewPager;
import com.ykdl.member.views.PhotoView;

public class LookAngleImageActivity extends BaseActivity implements OnClickListener {
	
	private static final String TAG = LookAngleImageActivity.class.getSimpleName();
	private ArrayList<DiaryBean> mImgList ;
	private List<Bitmap> mBmpList = new ArrayList<Bitmap>();
	private BitmapUtils mBitmapUtils ;
	private HackyViewPager mViewPager;
	private SamplePagerAdapter mAdapter;
	private LinearLayout mLayerImage;
	private boolean mSelf;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mSelf = getIntent().getBooleanExtra("self", true);
		initView();
		mBitmapUtils = new BitmapUtils(this);
		mAdapter = new SamplePagerAdapter();
		mImgList =  (ArrayList<DiaryBean>) getIntent().getSerializableExtra("list");
		int item = getIntent().getIntExtra("position", 0);
		mViewPager = new HackyViewPager(this);
		mViewPager.setAdapter(mAdapter);
		mViewPager.setCurrentItem(item);
		mLayerImage.addView(mViewPager);
	}
	
	private void initView(){
		setContentView(R.layout.layout_angle_image);
		findViewById(R.id.btnBack).setOnClickListener(this);
		if (mSelf) {
			findViewById(R.id.btnDelete).setOnClickListener(this);
			findViewById(R.id.btnSave).setOnClickListener(this);
		} else {
			findViewById(R.id.btnDelete).setVisibility(View.GONE);
			findViewById(R.id.btnSave).setVisibility(View.GONE);
		}
		mLayerImage = (LinearLayout) findViewById(R.id.layerImage);
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btnBack:
			finish();
			break;
		case R.id.btnDelete:
			long diary_id = mImgList.get(mViewPager.getCurrentItem()).getDiary_id();
			Network.getInstance().delDiary(diary_id, new DeleteTag());
			break;
		case R.id.btnSave:
			int posi = mViewPager.getCurrentItem();
			DiaryBean diary = mImgList.get(posi);
			saveImageInSDCard(null, diary.getFile_metas().get(0).getFile_name());
			break;
		default:
			break;
		}
		
	}
	
	private void saveImageInSDCard(Bitmap bmp, String fileName) {
		if (bmp == null) {
			Toast.makeText(this, "保存失败", 1).show();
			return;
		}
		if (!SysUtil.hasStorage()) {
			return;
		}
		File rootSD = Environment.getExternalStorageDirectory();
		File labelDir = new File(rootSD.getAbsolutePath()
				+ File.separator
				+ "DCIM"
				+ File.separator
				+ KidApp
						.getInstance()
						.getResources()
						.getString(
								KidApp.getInstance()
										.getApplicationInfo().labelRes)
				+ File.separator);
		if (!labelDir.exists()) {
			labelDir.mkdir();
		}
		String folder = labelDir.getAbsolutePath();
		String filePath = folder + File.separator + fileName;
		// ContentResolver cr = this.getContentResolver();
		// Cursor cursor = cr.query(Images.Media.EXTERNAL_CONTENT_URI, null,
		// Images.Media.DATA, new String[]{filePath}, null);
		if (ImageUtil.saveImage(bmp, filePath)) {
			ContentValues values = new ContentValues(7);
			int[] degree = { 0, 90, 180, 270 };
			values.put(Images.Media.TITLE, fileName);
			values.put(Images.Media.DISPLAY_NAME, fileName);
			values.put(Images.Media.DATE_TAKEN, new Date().getTime());
			values.put(Images.Media.MIME_TYPE, "image/jpeg");
			values.put(Images.Media.ORIENTATION, degree[0]);
			values.put(Images.Media.DATA, filePath);
			// values.put(Images.Media.SIZE, );
			this.getContentResolver().insert(Images.Media.EXTERNAL_CONTENT_URI,
					values);
			sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
					Uri.parse("file://"
							+ Environment.getExternalStorageDirectory())));
			Toast.makeText(this, "保存成功", 1).show();
		} else {
			Toast.makeText(this, "保存失败", 1).show();
		}

	}
	
	private class DeleteTag implements ITag<StatuResult> {

		@Override
		public void refreshUI(StatuResult t, DataState ds) {
			if (t != null && t.getResult() == 0 && TextUtils.isEmpty(t.getDesc())) {
				Toast.makeText(LookAngleImageActivity.this, "删除日记照片成功", 1).show();
			} else {
				if (TextUtils.isEmpty(t.getDesc())) {
					Toast.makeText(LookAngleImageActivity.this, "删除日记照片失败", 1).show();
				} else {
					Toast.makeText(LookAngleImageActivity.this, t.getDesc(), 1).show();
				}
			}
		}

		@Override
		public boolean refreshError(DataParseError parseError) {
			Toast.makeText(LookAngleImageActivity.this, "删除日记照片失败", 1).show();
			return false;
		}

		@Override
		public void refreshCancel() {
			
		}
		
	}
	
	private class SamplePagerAdapter extends PagerAdapter {

		@Override
		public int getCount() {
			if (mImgList!=null) {
				return mImgList.size();
			}else {
				return 0;
			}
		}

		@Override
		public View instantiateItem(ViewGroup container, int position) {
			PhotoView photoView = new PhotoView(container.getContext());
			String url = mImgList.get(position).getFile_metas().get(0).getDownload_urls().getOrigin().getUrl();
			mBitmapUtils.display(photoView, url);
			container.addView(photoView, LayoutParams.FILL_PARENT,
					LayoutParams.FILL_PARENT);
			//mBmpList.add(drawableToBitmap(photoView.getDrawable()));
			return photoView;
		}

		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
			container.removeView((View) object);
		}

		@Override
		public boolean isViewFromObject(View view, Object object) {
			return view == object;
		}

	}
	
	public Bitmap drawableToBitmap(Drawable drawable) {
		BitmapDrawable bd = (BitmapDrawable) drawable;
		Bitmap bm = bd.getBitmap();
        return bm;
	}

}
